<template>
  <div class="intelligence-graph-page">
    <div class="graph-content">
      <!-- 左侧筛选面板 -->
      <div class="filter-panel">
        <div class="filter-section">
          <h3>筛选条件</h3>

          <!-- 时间范围 -->
          <div class="filter-item">
            <label>时间范围:</label>
            <el-select
              v-model="filters.timeRange"
              @change="handleFilterChange"
              clearable
            >
              <el-option
                v-for="range in filterOptions.timeRanges"
                :key="range.value"
                :label="range.label"
                :value="range.value"
              />
            </el-select>
          </div>

          <!-- 严重程度 -->
          <div class="filter-item">
            <label>严重程度:</label>
            <el-checkbox-group
              v-model="filters.severity"
              @change="handleFilterChange"
            >
              <el-checkbox
                v-for="level in filterOptions.severityLevels"
                :key="level.value"
                :label="level.value"
                :disabled="!level.enabled"
              >
                <span :style="{ color: level.color }">{{ level.label }}</span>
              </el-checkbox>
            </el-checkbox-group>
          </div>

          <!-- 情报源 -->
          <div class="filter-item">
            <label>情报源:</label>
            <el-checkbox-group
              v-model="filters.sources"
              @change="handleFilterChange"
            >
              <el-checkbox
                v-for="source in filterOptions.sources"
                :key="source.value"
                :label="source.value"
              >
                {{ source.label }} ({{ source.count }})
              </el-checkbox>
            </el-checkbox-group>
          </div>

          <!-- 数据量限制 -->
          <div class="filter-item">
            <label>数据量限制:</label>
            <el-select
              v-model="filters.limit"
              @change="handleFilterChange"
              clearable
            >
              <el-option
                v-for="opt in filterOptions.limitOptions"
                :key="opt.value"
                :label="opt.label"
                :value="opt.value"
              />
            </el-select>
          </div>

          <!-- 显示资产 -->
          <div class="filter-item">
            <label>显示资产:</label>
            <el-switch
              v-model="filters.includeAssets"
              @change="handleFilterChange"
            />
          </div>

          <div class="filter-actions">
            <el-button @click="resetFilters">重置</el-button>
            <el-button type="primary" @click="applyFilters">应用筛选</el-button>
          </div>
        </div>

        <!-- 节点统计 -->
        <div class="statistics-section">
          <h3>节点统计</h3>
          <ul>
            <li>情报源: {{ statistics.sourceCount }}个</li>
            <li>情报: {{ statistics.intelligenceCount }}条</li>
            <li>资产: {{ statistics.assetCount }}个</li>
            <li>CVE: {{ statistics.cveCount }}个</li>
          </ul>
        </div>

        <!-- 图例 -->
        <div class="legend-section">
          <h3>图例</h3>
          <ul>
            <li>
              <span class="legend-icon source"></span>
              <span>情报源</span>
            </li>
            <li>
              <span class="legend-icon intelligence"></span>
              <span>威胁情报</span>
            </li>
            <li>
              <span class="legend-icon asset"></span>
              <span>资产</span>
            </li>
            <li>
              <span class="legend-icon cve"></span>
              <span>CVE</span>
            </li>
          </ul>
        </div>
      </div>

      <!-- 中间图谱区域 -->
      <div class="graph-area">
        <div class="graph-toolbar">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索节点..."
            @keyup.enter="searchNodes"
            class="search-input"
          >
            <template #append>
              <el-button @click="searchNodes"> 搜索 </el-button>
            </template>
          </el-input>

          <div class="graph-actions">
            <!-- <el-select
              v-model="currentLayout"
              @change="changeLayout"
              style="width: 120px; margin-right: 10px"
            >
              <el-option label="环形布局" value="circular" />
              <el-option label="力导向" value="force" />
            </el-select> -->

            <el-button @click="refreshGraph"> 刷新图谱 </el-button>
            <el-button @click="exportGraphPNG"> 导出图谱 </el-button>
            <!-- <el-button @click="autoLayout"> 自动布局 </el-button> -->
          </div>
        </div>

        <div class="graph-container">
          <div ref="graphChartRef" class="echarts-graph"></div>
        </div>

        <!-- 节点提示框 -->
        <div
          v-if="showTooltip"
          class="node-tooltip"
          :style="{
            left: tooltipPosition.left + 'px',
            top: tooltipPosition.top + 'px',
          }"
        >
          <div class="tooltip-title">{{ tooltipData.title }}</div>
          <div class="tooltip-content">
            <p v-for="(value, key) in tooltipData.content" :key="key">
              <span class="tooltip-key">{{ key }}:</span> {{ value }}
            </p>
          </div>
        </div>
      </div>

      <!-- 右侧详情面板 -->
      <div v-if="detailVisible" class="detail-panel">
        <div class="detail-header">
          <h3>节点详情</h3>
          <el-button
            icon="Close"
            text
            @click="detailVisible = false"
            class="close-btn"
          />
        </div>

        <div class="detail-content">
          <!-- 加载状态 -->
          <el-skeleton v-if="loadingDetail" :rows="8" style="width: 100%" />

          <!-- 情报节点详情 -->
          <template v-else-if="nodeDetail.node_type === 'intelligence'">
            <el-descriptions :column="1" border>
              <el-descriptions-item label="CVE ID">
                {{ nodeDetail.basic_info.cve_id }}
              </el-descriptions-item>
              <el-descriptions-item label="漏洞名称">
                {{ nodeDetail.basic_info.vul_name }}
              </el-descriptions-item>
              <el-descriptions-item label="CVSS评分">
                <el-tag
                  :type="getSeverityType(nodeDetail.basic_info.cvss_score)"
                >
                  {{ nodeDetail.basic_info.cvss_score }} ({{
                    nodeDetail.basic_info.severity_name
                  }})
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="来源">
                {{ nodeDetail.basic_info.source }}
              </el-descriptions-item>
              <el-descriptions-item label="发布时间">
                {{ nodeDetail.basic_info.published_at }}
              </el-descriptions-item>
            </el-descriptions>

            <div class="detail-section">
              <h4>漏洞描述</h4>
              <p>{{ nodeDetail.description }}</p>
            </div>

            <div class="detail-section">
              <h4>影响资产 ({{ nodeDetail.affected_assets?.length || 0 }})</h4>
              <el-table
                :data="nodeDetail.affected_assets || []"
                size="small"
                border
              >
                <el-table-column label="IP" prop="asset_ip" />
                <el-table-column label="服务" prop="asset_service" />
                <el-table-column label="部门" prop="department" />
                <el-table-column label="匹配度" prop="match_score">
                  <template #default="{ row }">
                    {{ (row.match_score * 100).toFixed(0) }}%
                  </template>
                </el-table-column>
              </el-table>
            </div>

            <div class="detail-actions">
              <el-button type="primary" @click="viewFullDetail">
                查看完整详情
              </el-button>
              <el-button @click="jumpToIntelligence"> 跳转情报库 </el-button>
            </div>
          </template>

          <!-- 资产节点详情 -->
          <template v-else-if="nodeDetail.node_type === 'asset'">
            <el-descriptions :column="1" border>
              <el-descriptions-item label="资产IP">
                {{ nodeDetail.basic_info.asset_ip }}
              </el-descriptions-item>
              <el-descriptions-item label="服务">
                {{ nodeDetail.basic_info.asset_service }}
              </el-descriptions-item>
              <el-descriptions-item label="部门">
                {{ nodeDetail.basic_info.department }}
              </el-descriptions-item>
              <el-descriptions-item label="责任人">
                {{ nodeDetail.basic_info.responsible_person }}
              </el-descriptions-item>
              <el-descriptions-item label="风险评分">
                <el-tag :type="getRiskType(nodeDetail.risk_info.risk_score)">
                  {{ nodeDetail.risk_info.risk_score }}分
                </el-tag>
              </el-descriptions-item>
            </el-descriptions>

            <div class="detail-section">
              <h4>
                关联情报 ({{ nodeDetail.related_intelligence?.length || 0 }})
              </h4>
              <el-table
                :data="nodeDetail.related_intelligence || []"
                size="small"
                border
              >
                <el-table-column label="CVE ID" prop="cve_id" />
                <el-table-column label="漏洞名称" prop="vul_name" />
                <el-table-column label="CVSS" prop="cvss_score" />
              </el-table>
            </div>
          </template>

          <!-- 情报源节点详情 -->
          <template v-else-if="nodeDetail.node_type === 'source'">
            <el-descriptions :column="1" border>
              <el-descriptions-item label="情报源名称">
                {{ nodeDetail.label }}
              </el-descriptions-item>
              <el-descriptions-item label="情报数量">
                {{ nodeDetail.metadata.total_intelligence }}条
              </el-descriptions-item>
              <el-descriptions-item label="活跃状态">
                <el-tag type="success" v-if="nodeDetail.metadata.active"
                  >活跃</el-tag
                >
                <el-tag type="info" v-else>不活跃</el-tag>
              </el-descriptions-item>
            </el-descriptions>

            <div class="detail-section">
              <h4>情报分布</h4>
              <el-table
                :data="nodeDetail.severity_distribution || []"
                size="small"
                border
              >
                <el-table-column label="严重程度" prop="severity" />
                <el-table-column label="数量" prop="count" />
                <el-table-column label="占比" prop="percentage">
                  <template #default="{ row }">
                    {{ row.percentage }}%
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </template>

          <!-- CVE节点详情 -->
          <template v-else-if="nodeDetail.node_type === 'cve'">
            <el-descriptions :column="1" border>
              <el-descriptions-item label="CVE ID">
                {{ nodeDetail.label }}
              </el-descriptions-item>
              <el-descriptions-item label="CVSS评分">
                {{ nodeDetail.metadata.cvss_score }}
              </el-descriptions-item>
              <el-descriptions-item label="EPSS评分">
                {{ nodeDetail.metadata.epss_score }}
              </el-descriptions-item>
            </el-descriptions>

            <div class="detail-section">
              <h4>关联情报源</h4>
              <el-tag
                v-for="source in nodeDetail.related_sources"
                :key="source.id"
                style="margin: 5px"
              >
                {{ source.label }}
              </el-tag>
            </div>
          </template>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick, onUnmounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useECharts } from "@pureadmin/utils";
import type { EChartsOption } from "echarts";
import type { Ref } from "vue";

// API调用
import {
  getIntelligenceGraphData,
  getFilterOptions,
  getNodeDetail,
  searchNodes as apiSearchNodes,
  exportGraph as apiExportGraph,
  getStatistics,
} from "../../servers";

// 页面状态
const username = ref("张三");
const activeTab = ref("intelligence");
const loading = ref(false);
const loadingDetail = ref(false);
const detailVisible = ref(false);
const nodeDetail = ref<any>({});
const searchKeyword = ref("");
const currentLayout = ref("force");
const graphChartRef = ref<HTMLDivElement>();
let chartInstance: any = null;
const showTooltip = ref(false);
const tooltipData = ref({ title: "", content: {} });
const tooltipPosition = ref({ left: 0, top: 0 });

// 筛选条件
const filters = reactive({
  timeRange: "30d",
  severity: ["critical", "high"],
  sources: ["NVD", "AVD"],
  limit: 50,
  includeAssets: true,
});

// 筛选选项
const filterOptions = reactive({
  timeRanges: [
    { value: "7天", label: "最近7天" },
    { value: "30天", label: "最近30天" },
    { value: "90天", label: "最近90天" },
    { value: "custom", label: "自定义" },
  ],
  severityLevels: [
    { value: "critical", label: "严重", color: "#ff4d4f", enabled: true },
    { value: "high", label: "高危", color: "#faad14", enabled: true },
    { value: "medium", label: "中危", color: "#ffd666", enabled: true },
    { value: "low", label: "低危", color: "#52c41a", enabled: true },
  ],
  sources: [
    { value: "NVD", label: "NVD", count: 45 },
    { value: "AVD", label: "阿里云漏洞库", count: 23 },
    { value: "GitHub", label: "GitHub Advisory", count: 12 },
    { value: "Manual", label: "手工添加", count: 5 },
  ],
  limitOptions: [
    { value: 10, label: "10条" },
    { value: 30, label: "30条" },
    { value: 50, label: "50条" },
    { value: 100, label: "100条" },
  ],
});

// 统计数据
const statistics = reactive({
  sourceCount: 0,
  intelligenceCount: 0,
  assetCount: 0,
  cveCount: 0,
});

// ECharts 图表实例
const { setOptions, getInstance, resize } = useECharts(
  graphChartRef as Ref<HTMLDivElement>
);

// 获取节点样式
const getNodeStyle = (
  nodeType: string,
  severity?: string,
  cvssScore?: number
) => {
  const styles: any = {
    source: {
      shape: "rect",
      size: [120, 60],
      color: "#1890ff",
      borderColor: "#fff",
      fontColor: "#fff",
      fontSize: 14,
    },
    intelligence: {
      shape: "rect",
      size: cvssScore ? [100 + cvssScore * 5, 50] : [100, 50],
      color: "#faad14",
      borderColor: "#fff",
      fontColor: "#fff",
      fontSize: 12,
    },
    asset: {
      shape: "rect",
      size: [120, 60],
      color: "#52c41a",
      borderColor: "#fff",
      fontColor: "#333",
      fontSize: 12,
    },
    cve: {
      shape: "rect",
      size: [100, 50],
      color: "#722ed1",
      borderColor: "#fff",
      fontColor: "#fff",
      fontSize: 11,
    },
  };

  // 根据严重程度设置情报节点颜色
  if (nodeType === "intelligence" && severity) {
    if (severity === "critical" || (cvssScore && cvssScore >= 9.0)) {
      styles.intelligence.color = "#ff4d4f";
    } else if (severity === "high" || (cvssScore && cvssScore >= 7.0)) {
      styles.intelligence.color = "#faad14";
    } else if (severity === "medium" || (cvssScore && cvssScore >= 4.0)) {
      styles.intelligence.color = "#ffd666";
    } else {
      styles.intelligence.color = "#52c41a";
    }
  }

  return styles[nodeType] || styles.intelligence;
};

// 获取边样式
const getEdgeStyle = (edgeType: string) => {
  const styles: any = {
    publishes: {
      color: "#1890ff",
      width: 2,
      style: "solid",
    },
    affects: {
      color: "#ff4d4f",
      width: 3,
      style: "solid",
    },
    has_cve: {
      color: "#722ed1",
      width: 1,
      style: "dashed",
    },
  };

  return styles[edgeType] || styles.publishes;
};

// 转换API数据为ECharts Graph格式
const transformGraphData = (apiData: any) => {
  if (!apiData) {
    return { nodes: [], links: [] };
  }

  const nodes = Array.isArray(apiData.nodes) ? apiData.nodes : [];
  const edges = Array.isArray(apiData.edges) ? apiData.edges : [];

  // 转换节点为ECharts格式
  const echartsNodes = nodes.map((node: any) => {
    const style = getNodeStyle(node.type, node.severity, node.cvss_score);
    const size = style.size instanceof Array ? style.size[0] : style.size;
    const height = style.size instanceof Array ? style.size[1] : size;

    return {
      id: node.id,
      name: node.label || node.id,
      symbolSize: [size, height], // 使用数组设置矩形大小 [宽度, 高度]
      symbol: "rect", // 使用矩形符号
      itemStyle: {
        color: style.color,
        borderColor: style.borderColor,
        borderWidth: 2,
      },
      label: {
        show: true,
        position: "inside",
        color: style.fontColor,
        fontSize: style.fontSize,
        formatter: (params: any) => {
          const name = params.name || "";
          // 如果名称太长，换行显示
          if (name.length > 15) {
            return name.substring(0, 15) + "\n" + name.substring(15);
          }
          return name;
        },
      },
      category: node.type,
      value: node.cvss_score || 0,
      nodeType: node.type,
      metadata: node.metadata || {},
      severity: node.severity,
      cvssScore: node.cvss_score,
    };
  });

  // 转换边为ECharts格式
  const echartsLinks = edges.map((edge: any) => {
    const style = getEdgeStyle(edge.type);

    return {
      source: edge.source,
      target: edge.target,
      lineStyle: {
        color: style.color,
        width: style.width,
        type: style.style === "dashed" ? "dashed" : "solid",
      },
      edgeType: edge.type,
      matchScore: edge.match_score,
    };
  });

  return { nodes: echartsNodes, links: echartsLinks };
};

// 渲染ECharts图谱
const renderGraph = (nodes: any[], links: any[]) => {
  const option: EChartsOption = {
    tooltip: {
      show: true,
      formatter: (params: any) => {
        if (params.dataType === "node") {
          const node = params.data;
          let content = `<div style="font-weight: bold; margin-bottom: 5px;">${node.name}</div>`;
          if (node.nodeType === "intelligence") {
            content += `<div>严重程度: ${node.severity || "未知"}</div>`;
            content += `<div>CVSS评分: ${node.cvssScore || "未知"}</div>`;
          } else if (node.nodeType === "asset") {
            content += `<div>IP: ${node.metadata?.ip || "未知"}</div>`;
            content += `<div>服务: ${node.metadata?.service || "未知"}</div>`;
          }
          return content;
        }
        return params.data.label?.formatter || "";
      },
    },
    series: [
      {
        type: "graph",
        layout: currentLayout.value === "force" ? "force" : "circular",
        data: nodes,
        links: links,
        categories: [
          { name: "source", itemStyle: { color: "#1890ff" } },
          { name: "intelligence", itemStyle: { color: "#faad14" } },
          { name: "asset", itemStyle: { color: "#52c41a" } },
          { name: "cve", itemStyle: { color: "#722ed1" } },
        ],
        roam: true,
        label: {
          show: true,
          position: "inside",
          formatter: "{b}",
          fontSize: 12,
        },
        labelLayout: {
          hideOverlap: false,
        },
        emphasis: {
          focus: "adjacency",
          lineStyle: {
            width: 4,
          },
        },
        lineStyle: {
          curveness: 0.3,
        },
        force: {
          repulsion: 2000,
          gravity: 0.1,
          edgeLength: 150,
          layoutAnimation: true,
        },
        circular: {
          rotateLabel: true,
        },
      },
    ],
  };

  setOptions(option);
  chartInstance = getInstance();
  setupChartEvents(); // 设置事件监听
};

// 加载图谱数据
const loadGraphData = async () => {
  try {
    loading.value = true;

    // 构建请求参数
    const params = {
      time_range: filters.timeRange,
      severity_filter: filters.severity,
      source_filter: filters.sources,
      limit: filters.limit,
      include_assets: filters.includeAssets,
    };

    const res = await getIntelligenceGraphData(params);
    if (res.code === 2000) {
      const { nodes, links } = transformGraphData(res.data);

      // 更新统计数据
      if (res.data.statistics) {
        statistics.sourceCount = res.data.statistics.source_count || 0;
        statistics.intelligenceCount =
          res.data.statistics.intelligence_count || 0;
        statistics.assetCount = res.data.statistics.asset_count || 0;
        statistics.cveCount = res.data.statistics.cve_count || 0;
      }

      // 渲染图谱
      await nextTick();
      if (nodes.length > 0) {
        renderGraph(nodes, links);
      } else {
        ElMessage.warning("暂无数据");
      }
    }
  } catch (error: any) {
    ElMessage.error(error?.message || "获取图谱数据失败");
  } finally {
    loading.value = false;
  }
};

// 获取筛选选项
const loadFilterOptions = async () => {
  try {
    const res = await getFilterOptions();
    if (res.code === 2000) {
      // 更新筛选选项
      if (res.data.time_ranges) {
        filterOptions.timeRanges = res.data.time_ranges.map((item: any) => ({
          value: item.value,
          label: item.label,
        }));
      }

      if (res.data.severity_levels) {
        filterOptions.severityLevels = res.data.severity_levels.map(
          (item: any) => ({
            value: item.value,
            label: item.label,
            color: item.color,
            enabled: true,
          })
        );
      }

      if (res.data.sources) {
        filterOptions.sources = res.data.sources.map((item: any) => ({
          value: item.value,
          label: item.label,
          count: item.count,
        }));
      }
    }
  } catch (error: any) {
    console.error("获取筛选选项失败:", error);
  }
};

// 获取统计数据
const loadStatistics = async () => {
  try {
    const res = await getStatistics({ time_range: filters.timeRange });
    if (res.code === 2000) {
      // 可以在这里更新额外的统计信息
    }
  } catch (error: any) {
    console.error("获取统计数据失败:", error);
  }
};

// 节点点击事件（通过ECharts事件绑定）
const setupChartEvents = () => {
  if (!chartInstance) return;

  chartInstance.off("click");
  chartInstance.on("click", async (params: any) => {
    if (params.dataType === "node") {
      const node = params.data;
      try {
        loadingDetail.value = true;
        const res = await getNodeDetail({
          node_id: node.id,
          node_type: node.nodeType,
        });

        if (res.code === 2000) {
          nodeDetail.value = res.data;
          detailVisible.value = true;
        }
      } catch (error: any) {
        ElMessage.error(error?.message || "获取节点详情失败");
      } finally {
        loadingDetail.value = false;
      }
    } else if (params.dataType === "edge") {
      const link = params.data;
      ElMessage.info(`关系: ${link.label?.formatter || link.edgeType}`);
    }
  });
};

// 搜索节点
const searchNodes = async () => {
  if (!searchKeyword.value.trim()) {
    ElMessage.warning("请输入搜索关键词");
    return;
  }

  try {
    const res = await apiSearchNodes({
      keyword: searchKeyword.value,
      limit: 20,
    });

    if (res.code === 2000 && res.data.results.length > 0) {
      // 高亮第一个匹配的节点
      const firstNodeId = res.data.results[0].node_id;
      if (chartInstance) {
        // 使用ECharts的dispatchAction高亮节点
        chartInstance.dispatchAction({
          type: "highlight",
          dataIndex: chartInstance
            .getOption()
            .series[0].data.findIndex((n: any) => n.id === firstNodeId),
        });

        // 3秒后取消高亮
        setTimeout(() => {
          if (chartInstance) {
            chartInstance.dispatchAction({
              type: "downplay",
              dataIndex: chartInstance
                .getOption()
                .series[0].data.findIndex((n: any) => n.id === firstNodeId),
            });
          }
        }, 3000);
      }
    } else {
      ElMessage.info("未找到匹配的节点");
    }
  } catch (error: any) {
    ElMessage.error(error?.message || "搜索节点失败");
  }
};

// 刷新图谱
const refreshGraph = () => {
  loadGraphData();
};

// 切换布局
const changeLayout = (layoutName: string) => {
  currentLayout.value = layoutName;
  loadGraphData(); // 重新加载数据以应用新布局
};

// 自动布局
const autoLayout = () => {
  if (chartInstance) {
    // ECharts会自动重新布局
    chartInstance.resize();
  }
};

// 导出图谱PNG
const exportGraphPNG = () => {
  if (chartInstance) {
    const url = chartInstance.getDataURL({
      type: "png",
      pixelRatio: 2,
      backgroundColor: "#fff",
    });
    const link = document.createElement("a");
    link.href = url;
    link.download = `intelligence_graph_${new Date().getTime()}.png`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    ElMessage.success("图谱导出成功");
  }
};

// 导出JSON数据
const exportGraphJSON = async () => {
  try {
    const params = {
      format: "json",
      time_range: filters.timeRange,
      severity_filter: filters.severity,
      source_filter: filters.sources,
      limit: filters.limit,
      include_assets: filters.includeAssets,
    };

    const res = await apiExportGraph(params);
    if (res.data) {
      // 创建下载链接
      const blob = new Blob([JSON.stringify(res.data, null, 2)], {
        type: "application/json",
      });
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = `intelligence_graph_${new Date().getTime()}.json`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);

      ElMessage.success("JSON数据导出成功");
    }
  } catch (error: any) {
    ElMessage.error(error?.message || "导出JSON数据失败");
  }
};

// 筛选相关方法
const handleFilterChange = () => {
  // 可以在这里添加防抖处理
};

const applyFilters = () => {
  loadGraphData();
};

const resetFilters = () => {
  filters.timeRange = "30d";
  filters.severity = ["critical", "high"];
  filters.sources = ["NVD", "AVD"];
  filters.limit = 50;
  filters.includeAssets = true;

  // 重新加载数据
  loadGraphData();
};

// 节点详情页操作
const viewFullDetail = () => {
  // 查看完整详情逻辑
  ElMessage.info("跳转到完整详情页面");
};

const jumpToIntelligence = () => {
  // 跳转到情报库逻辑
  ElMessage.info("跳转到情报库");
};

// 辅助方法：根据评分获取严重程度标签类型
const getSeverityType = (score: number) => {
  if (score >= 9.0) return "danger";
  if (score >= 7.0) return "warning";
  if (score >= 4.0) return "info";
  return "success";
};

// 辅助方法：根据风险评分获取标签类型
const getRiskType = (score: number) => {
  if (score >= 80) return "danger";
  if (score >= 60) return "warning";
  if (score >= 40) return "info";
  return "success";
};

// 初始化
onMounted(async () => {
  await loadFilterOptions();
  await loadStatistics();
  // 等待组件初始化完成
  await nextTick();
  await loadGraphData();
});

// 组件卸载时清理
onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose();
  }
});

// 暴露 resizeChart 方法供父组件调用
const resizeChart = () => {
  if (chartInstance) {
    chartInstance.resize();
  }
};

defineExpose({
  resizeChart,
});
</script>

<style scoped lang="scss">
.intelligence-graph-page {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
  box-sizing: border-box;
}

.navbar-card {
  margin-bottom: 20px;
  border-radius: 8px;

  .navbar-content {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .page-title {
      font-size: 18px;
      font-weight: 600;
      margin: 0;
      color: #333;
    }

    .user-info {
      color: #666;
      font-size: 14px;
    }
  }
}

.tabs-container {
  margin-bottom: 20px;
  background-color: #fff;
  border-radius: 8px;
  padding: 10px 20px 0;
}

.graph-content {
  display: flex;
  gap: 20px;
  height: calc(100vh - 150px);
}

.filter-panel {
  width: 280px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 20px;
  overflow-y: auto;
}

.filter-section {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.filter-item {
  display: flex;
  flex-direction: column;
  gap: 8px;

  label {
    font-size: 14px;
    color: #666;
    font-weight: 500;
  }

  .el-select,
  .el-input {
    width: 100%;
  }
}

.filter-actions {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}

.statistics-section,
.legend-section {
  background-color: #f9f9f9;
  border-radius: 6px;
  padding: 12px;

  h3 {
    font-size: 14px;
    color: #333;
    margin-bottom: 10px;
    font-weight: 500;
  }

  ul {
    list-style: none;
    padding: 0;
    margin: 0;

    li {
      font-size: 13px;
      color: #666;
      margin-bottom: 6px;
      display: flex;
      align-items: center;
      gap: 8px;
    }
  }
}

.legend-icon {
  display: inline-block;
  width: 12px;
  height: 12px;
  border-radius: 50%;

  &.source {
    background-color: #1890ff;
  }

  &.intelligence {
    background-color: #faad14;
  }

  &.asset {
    background-color: #52c41a;
    border-radius: 2px;
  }

  &.cve {
    background-color: #722ed1;
    border-radius: 0;
    transform: rotate(45deg);
  }
}

.graph-area {
  flex: 1;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.graph-toolbar {
  padding: 10px 16px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 10px;
}

.search-input {
  width: 300px;
}

.graph-actions {
  display: flex;
  align-items: center;
  gap: 5px;
}

.graph-container {
  flex: 1;
  position: relative;
  overflow: hidden;
}

.echarts-graph {
  width: 100%;
  height: 100%;
  min-height: 600px;
}

.node-tooltip {
  position: absolute;
  background-color: rgba(0, 0, 0, 0.8);
  color: #fff;
  padding: 8px 12px;
  border-radius: 4px;
  font-size: 12px;
  z-index: 1000;
  pointer-events: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  max-width: 250px;

  .tooltip-title {
    font-weight: bold;
    margin-bottom: 5px;
    padding-bottom: 5px;
    border-bottom: 1px solid rgba(255, 255, 255, 0.3);
  }

  .tooltip-content {
    p {
      margin: 3px 0;
      line-height: 1.4;

      .tooltip-key {
        color: #ccc;
        display: inline-block;
        width: 60px;
      }
    }
  }
}

.detail-panel {
  width: 400px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.detail-header {
  padding: 12px 16px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;

  h3 {
    margin: 0;
    font-size: 16px;
    color: #333;
  }

  .close-btn {
    color: #999;
  }
}

.detail-content {
  flex: 1;
  padding: 16px;
  overflow-y: auto;

  .detail-section {
    margin-top: 16px;

    h4 {
      font-size: 14px;
      color: #333;
      margin-bottom: 8px;
      font-weight: 500;
    }
  }

  .detail-actions {
    margin-top: 20px;
    display: flex;
    gap: 10px;
  }
}

.el-table {
  font-size: 12px;

  .el-table__cell {
    padding: 6px 0;
  }
}

.el-descriptions {
  margin-bottom: 16px;

  .el-descriptions__label {
    font-weight: 500;
  }
}

@media (max-width: 1600px) {
  .filter-panel {
    width: 240px;
  }

  .detail-panel {
    width: 350px;
  }

  .search-input {
    width: 220px;
  }
}
</style>
